import config from '@/config/app.js'
import api from './api'

const {
	HTTP_REQUEST_URL,
	REDIRECT_PATH,
	TOKENNAME,
	HEADER,
} = config

const pathParse = (apiModule) => {
	let mArr = apiModule.split('.')
	return mArr.reduce((prev, current) => prev[current], api)
}

export const service = (apiModule, data) => {
	const {
		path,
		method
	} = pathParse(apiModule)
	uni.showLoading({
		title: '加载中'
	})
	return new Promise((resolved, rejected) => {
		uni.request({
			url: `${HTTP_REQUEST_URL}${path}`,
			data: data,
			method: method,
			header: {
				...HEADER,
				[TOKENNAME]: `Bearer ${uni.getStorageSync('token')}`
			},
			timeout: 10000,
			success: (res) => {
				if (res.data.statusCode == 401) {
					uni.reLaunch({
						url: REDIRECT_PATH
					})
				} else if (res.data.statusCode != 200) {
					// uni.showToast({
					// 	title: res.data.message,
					// 	icon: 'none'
					// })
				}
				resolved(res)
			},
			fail: (err) => {
				uni.showModal({
					title: '提示',
					showCancel: false,
					content: '请求超时'
				})
				rejected(err)
			},
			complete: ()=> {
				uni.hideLoading()
			}
		});
	})
}
